package com.waikuai.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waikuai.shop.dto.CreateOrderDTO;
import com.waikuai.shop.dto.OrderQueryDTO;
import com.waikuai.shop.entity.*;
import com.waikuai.shop.mapper.*;
import com.waikuai.shop.service.OrderService;
import com.waikuai.shop.service.ShoppingCartService;
import com.waikuai.shop.vo.LogisticsVO;
import com.waikuai.shop.vo.OrderDetailVO;
import com.waikuai.shop.vo.OrderListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ShoppingCartService shoppingCartService;
    private final ProductMapper productMapper;
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(CreateOrderDTO createOrderDTO, Long userId) {
        try {
            // 1. 获取用户选中的购物车商品
            List<ShoppingCart> selectedItems = shoppingCartService.getSelectedItems(userId);
            if (selectedItems == null || selectedItems.isEmpty()) {
                log.warn("购物车中没有选中的商品，用户ID: {}", userId);
                throw new RuntimeException("购物车中没有选中的商品");
            }

            // 2. 验证商品库存
            for (ShoppingCart cartItem : selectedItems) {
                Product product = cartItem.getProduct();
                if (product == null) {
                    log.warn("购物车商品信息不存在，商品ID: {}", cartItem.getProductId());
                    throw new RuntimeException("购物车商品信息不存在");
                }
                if (product.getStockQuantity() < cartItem.getQuantity()) {
                    log.warn("商品库存不足，商品ID: {}, 库存: {}, 购买数量: {}",
                            product.getId(), product.getStockQuantity(), cartItem.getQuantity());
                    throw new RuntimeException("商品【" + product.getProductName() + "】库存不足");
                }
            }

            // 3. 计算订单总金额
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (ShoppingCart cartItem : selectedItems) {
                Product product = cartItem.getProduct();
                BigDecimal itemTotal = product.getPrice().multiply(new BigDecimal(cartItem.getQuantity()));
                totalAmount = totalAmount.add(itemTotal);
            }

            // 4. 生成订单号（时间戳+随机数）
            String orderNo = generateOrderNo();

            // 5. 创建订单记录
            Order order = new Order();
            order.setOrderNo(orderNo);
            order.setUserId(userId);
            order.setTotalAmount(totalAmount);
            order.setDiscountAmount(BigDecimal.ZERO);
            order.setActualAmount(totalAmount);
            order.setPaymentMethod(1); // 余额支付
            order.setPaymentStatus(0); // 未支付
            order.setOrderStatus(0); // 待支付
            order.setReceiverName(createOrderDTO.getReceiverName());
            order.setReceiverPhone(createOrderDTO.getReceiverPhone());
            order.setReceiverAddress(createOrderDTO.getReceiverAddress());
            order.setRemark(createOrderDTO.getRemark());

            int orderResult = orderMapper.insert(order);
            if (orderResult <= 0) {
                throw new RuntimeException("创建订单失败");
            }

            // 6. 批量创建订单明细（商品快照）
            List<OrderItem> orderItems = new ArrayList<>();
            for (ShoppingCart cartItem : selectedItems) {
                Product product = cartItem.getProduct();
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(order.getId());
                orderItem.setProductId(product.getId());
                orderItem.setProductName(product.getProductName());
                orderItem.setProductImage(product.getMainImage());
                orderItem.setUnitPrice(product.getPrice());
                orderItem.setQuantity(cartItem.getQuantity());
                orderItem.setTotalPrice(product.getPrice().multiply(new BigDecimal(cartItem.getQuantity())));
                orderItems.add(orderItem);
            }
            orderItemMapper.batchInsert(orderItems);

            // 7. 扣减商品库存
            for (ShoppingCart cartItem : selectedItems) {
                productMapper.updateStock(cartItem.getProductId(), -cartItem.getQuantity());
                // 增加商品销量
                productMapper.updateSalesCount(cartItem.getProductId(), cartItem.getQuantity());
            }

            // 8. 清空购物车（删除已结算商品）
            List<Long> productIds = selectedItems.stream()
                    .map(ShoppingCart::getProductId)
                    .collect(Collectors.toList());
            shoppingCartService.batchRemoveFromCart(userId, productIds);

            log.info("创建订单成功，订单号: {}, 用户ID: {}, 订单金额: {}", orderNo, userId, totalAmount);
            return order.getId();
        } catch (Exception e) {
            log.error("创建订单失败，用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            throw new RuntimeException("创建订单失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean payOrder(Long orderId, Long userId, String paymentPassword) {
        try {
            // 1. 查询订单
            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                log.warn("订单不存在，订单ID: {}", orderId);
                throw new RuntimeException("订单不存在");
            }

            // 2. 验证订单归属
            if (!order.getUserId().equals(userId)) {
                log.warn("订单不属于当前用户，订单ID: {}, 用户ID: {}", orderId, userId);
                throw new RuntimeException("订单不属于当前用户");
            }

            // 3. 验证订单状态
            if (order.getPaymentStatus() == 1) {
                log.warn("订单已支付，订单ID: {}", orderId);
                throw new RuntimeException("订单已支付");
            }

            if (order.getOrderStatus() == 5) {
                log.warn("订单已取消，无法支付，订单ID: {}", orderId);
                throw new RuntimeException("订单已取消，无法支付");
            }

            // 4. 查询用户信息
            User user = userMapper.selectById(userId);
            if (user == null) {
                log.warn("用户不存在，用户ID: {}", userId);
                throw new RuntimeException("用户不存在");
            }
            
            // 5. 验证支付密码
            if (paymentPassword == null || paymentPassword.trim().isEmpty()) {
                log.warn("支付密码不能为空，用户ID: {}", userId);
                throw new RuntimeException("请输入支付密码");
            }
            if (user.getPaymentPassword() == null || user.getPaymentPassword().isEmpty()) {
                log.warn("用户未设置支付密码，用户ID: {}", userId);
                throw new RuntimeException("请先设置支付密码");
            }
            if (!passwordEncoder.matches(paymentPassword, user.getPaymentPassword())) {
                log.warn("支付密码错误，用户ID: {}", userId);
                throw new RuntimeException("支付密码错误");
            }

            // 6. 验证用户余额
            BigDecimal userBalance = user.getAccountBalance() == null
                    ? BigDecimal.ZERO
                    : BigDecimal.valueOf(user.getAccountBalance());
            if (userBalance.compareTo(order.getActualAmount()) < 0) {
                log.warn("用户余额不足，用户ID: {}, 余额: {}, 订单金额: {}", userId, userBalance, order.getActualAmount());
                throw new RuntimeException("余额不足，请先充值");
            }

            // 7. 扣除用户余额
            LambdaUpdateWrapper<User> userUpdateWrapper = new LambdaUpdateWrapper<>();
            userUpdateWrapper.eq(User::getId, userId)
                           .setSql("account_balance = account_balance - " + order.getActualAmount());
            int balanceResult = userMapper.update(null, userUpdateWrapper);
            if (balanceResult <= 0) {
                throw new RuntimeException("扣除余额失败");
            }

            // 8. 更新订单支付状态、订单状态和支付时间
            LambdaUpdateWrapper<Order> orderUpdateWrapper = new LambdaUpdateWrapper<>();
            orderUpdateWrapper.eq(Order::getId, orderId)
                             .set(Order::getPaymentStatus, 1)
                             .set(Order::getPaymentTime, LocalDateTime.now()) // 记录支付时间
                             .set(Order::getOrderStatus, 1); // 支付后变为待发货
            int orderResult = orderMapper.update(null, orderUpdateWrapper);
            if (orderResult <= 0) {
                throw new RuntimeException("更新订单支付状态失败");
            }

            log.info("订单支付成功，订单ID: {}, 用户ID: {}, 支付金额: {}", orderId, userId, order.getActualAmount());
            return true;
        } catch (Exception e) {
            log.error("订单支付失败，订单ID: {}, 用户ID: {}, 错误: {}", orderId, userId, e.getMessage(), e);
            throw new RuntimeException("订单支付失败: " + e.getMessage());
        }
    }

    @Override
    public IPage<OrderListVO> getOrderPage(OrderQueryDTO queryDTO) {
        try {
            // 1. 先分页查询订单ID列表（只查订单表，不关联订单项）
            Page<Long> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
            IPage<Long> orderIdPage = orderMapper.selectOrderIdPageByUserId(
                    page, queryDTO.getUserId(), queryDTO.getOrderStatus());

            // 2. 如果没有数据，直接返回空结果
            if (orderIdPage.getRecords().isEmpty()) {
                return new Page<OrderListVO>(queryDTO.getCurrent(), queryDTO.getSize(), 0);
            }

            // 3. 根据订单ID列表查询完整的订单信息（包含订单项）
            List<Long> orderIds = orderIdPage.getRecords();
            List<Order> orders = orderMapper.selectOrdersByIds(orderIds);

            // 4. 转换为VO
            List<OrderListVO> orderListVOs = orders.stream()
                    .map(this::convertToOrderListVO)
                    .collect(Collectors.toList());

            // 5. 构建分页结果
            Page<OrderListVO> voPage = new Page<>(
                    orderIdPage.getCurrent(),
                    orderIdPage.getSize(),
                    orderIdPage.getTotal()
            );
            voPage.setRecords(orderListVOs);

            return voPage;
        } catch (Exception e) {
            log.error("分页查询订单列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订单列表失败");
        }
    }

    @Override
    public List<OrderListVO> getOrderList(Long userId, Integer orderStatus) {
        try {
            List<Order> orders;
            if (orderStatus != null) {
                orders = orderMapper.selectOrdersByUserIdAndStatus(userId, orderStatus);
            } else {
                orders = orderMapper.selectOrdersByUserId(userId);
            }

            // 转换为VO（去重，因为LEFT JOIN会产生重复记录）
            return orders.stream()
                    .collect(Collectors.toMap(
                            Order::getId,
                            this::convertToOrderListVO,
                            (existing, replacement) -> existing
                    ))
                    .values()
                    .stream()
                    .sorted((a,b) -> {
                        return b.getCreateTime().compareTo(a.getCreateTime());
                    })
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("查询订单列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订单列表失败");
        }
    }

    @Override
    public OrderDetailVO getOrderDetail(Long orderId, Long userId) {
        try {
            Order order = orderMapper.selectOrderDetailById(orderId);
            if (order == null) {
                log.warn("订单不存在，订单ID: {}", orderId);
                throw new RuntimeException("订单不存在");
            }

            // 验证订单归属
            if (!order.getUserId().equals(userId)) {
                log.warn("订单不属于当前用户，订单ID: {}, 用户ID: {}", orderId, userId);
                throw new RuntimeException("订单不属于当前用户");
            }

            return convertToOrderDetailVO(order);
        } catch (Exception e) {
            log.error("查询订单详情失败，订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("查询订单详情失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long orderId, Long userId) {
        try {
            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                log.warn("订单不存在，订单ID: {}", orderId);
                throw new RuntimeException("订单不存在");
            }

            // 验证订单归属
            if (!order.getUserId().equals(userId)) {
                log.warn("订单不属于当前用户，订单ID: {}, 用户ID: {}", orderId, userId);
                throw new RuntimeException("订单不属于当前用户");
            }

            // 验证订单状态
            if (order.getOrderStatus() == 4) {
                log.warn("订单已完成，无法取消，订单ID: {}", orderId);
                throw new RuntimeException("订单已完成，无法取消");
            }

            if (order.getOrderStatus() == 5) {
                log.warn("订单已取消，订单ID: {}", orderId);
                return true;
            }

            // 如果已支付，需要退款
            if (order.getPaymentStatus() == 1) {
                // 退还余额
                LambdaUpdateWrapper<User> userUpdateWrapper = new LambdaUpdateWrapper<>();
                userUpdateWrapper.eq(User::getId, userId)
                               .setSql("account_balance = account_balance + " + order.getActualAmount());
                userMapper.update(null, userUpdateWrapper);

                // 恢复商品库存
                List<OrderItem> orderItems = orderItemMapper.selectByOrderId(orderId);
                for (OrderItem item : orderItems) {
                    productMapper.updateStock(item.getProductId(), item.getQuantity());
                }
            }

            // 更新订单状态为已取消
            LambdaUpdateWrapper<Order> orderUpdateWrapper = new LambdaUpdateWrapper<>();
            orderUpdateWrapper.eq(Order::getId, orderId)
                             .set(Order::getOrderStatus, 5);
            int result = orderMapper.update(null, orderUpdateWrapper);
            if (result > 0) {
                log.info("取消订单成功，订单ID: {}", orderId);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("取消订单失败，订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("取消订单失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(Long orderId, Integer orderStatus) {
        try {
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Order::getId, orderId)
                       .set(Order::getOrderStatus, orderStatus);

            // 如果状态改为已发货，设置发货时间
            if (orderStatus == 2) {
                updateWrapper.set(Order::getShippingTime, LocalDateTime.now());
            }

            // 如果状态改为已完成，设置完成时间
            if (orderStatus == 4) {
                updateWrapper.set(Order::getCompletedTime, LocalDateTime.now());
            }

            int result = orderMapper.update(null, updateWrapper);
            if (result > 0) {
                log.info("更新订单状态成功，订单ID: {}, 新状态: {}", orderId, orderStatus);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("更新订单状态失败，订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("更新订单状态失败");
        }
    }

    @Override
    public LogisticsVO getOrderLogistics(Long orderId, Long userId) {
        try {
            Order order = orderMapper.selectById(orderId);
            if (order == null) {
                log.warn("订单不存在，订单ID: {}", orderId);
                throw new RuntimeException("订单不存在");
            }

            // 验证订单归属
            if (!order.getUserId().equals(userId)) {
                log.warn("订单不属于当前用户，订单ID: {}, 用户ID: {}", orderId, userId);
                throw new RuntimeException("订单不属于当前用户");
            }

            // 计算物流信息
            LogisticsVO logistics = calculateLogisticsInfo(order);
            log.info("获取订单物流信息成功，订单ID: {}", orderId);
            return logistics;
        } catch (Exception e) {
            log.error("获取订单物流信息失败，订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("获取订单物流信息失败: " + e.getMessage());
        }
    }

    /**
     * 生成订单号（时间戳+随机数）
     */
    private String generateOrderNo() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.format("%06d", new Random().nextInt(1000000));
        return "ORD" + timestamp + random;
    }

    /**
     * 转换为订单列表VO
     */
    private OrderListVO convertToOrderListVO(Order order) {
        OrderListVO vo = new OrderListVO();
        vo.setId(order.getId());
        vo.setOrderNo(order.getOrderNo());
        vo.setTotalAmount(order.getTotalAmount());
        vo.setActualAmount(order.getActualAmount());
        vo.setPaymentStatus(order.getPaymentStatus());
        
        // 动态计算订单状态（根据付款时间）
        Integer calculatedStatus = calculateOrderStatus(order);
        vo.setOrderStatus(calculatedStatus);
        
        vo.setCreateTime(order.getCreateTime());

        // 转换订单明细
        if (order.getOrderItems() != null && !order.getOrderItems().isEmpty()) {
            List<OrderListVO.OrderItemSimpleVO> itemVOs = order.getOrderItems().stream()
                    .map(item -> {
                        OrderListVO.OrderItemSimpleVO itemVO = new OrderListVO.OrderItemSimpleVO();
                        itemVO.setProductId(item.getProductId());
                        itemVO.setProductName(item.getProductName());
                        itemVO.setProductImage(item.getProductImage());
                        itemVO.setUnitPrice(item.getUnitPrice());
                        itemVO.setQuantity(item.getQuantity());
                        return itemVO;
                    })
                    .collect(Collectors.toList());
            vo.setOrderItems(itemVOs);
        }

        return vo;
    }

    /**
     * 根据付款时间动态计算订单状态
     * @param order 订单对象
     * @return 计算后的订单状态
     */
    private Integer calculateOrderStatus(Order order) {
        // 如果订单已取消或未支付，直接返回原状态
        if (order.getOrderStatus() == 5) {
            return 5; // 已取消
        }
        if (order.getPaymentStatus() == 0) {
            return 0; // 待支付
        }

        // 兼容旧数据：如果 paymentTime 为空，使用 createTime 作为备用
        LocalDateTime paymentTime = order.getPaymentTime() != null ? order.getPaymentTime() : order.getCreateTime();
        LocalDate paymentDate = paymentTime.toLocalDate();
        LocalDate today = LocalDate.now();
        long daysSincePayment = ChronoUnit.DAYS.between(paymentDate, today);

        // 根据支付后的天数计算状态
        if (daysSincePayment == 0) {
            return 1; // 待发货
        } else if (daysSincePayment == 1) {
            return 2; // 配送中
        } else if (daysSincePayment == 2) {
            return 3; // 待取件
        } else {
            return 4; // 已完成
        }
    }

    /**
     * 转换为订单详情VO
     */
    private OrderDetailVO convertToOrderDetailVO(Order order) {
        OrderDetailVO vo = new OrderDetailVO();
        vo.setId(order.getId());
        vo.setOrderNo(order.getOrderNo());
        vo.setTotalAmount(order.getTotalAmount());
        vo.setDiscountAmount(order.getDiscountAmount());
        vo.setActualAmount(order.getActualAmount());
        vo.setPaymentMethod(order.getPaymentMethod());
        vo.setPaymentStatus(order.getPaymentStatus());
        vo.setOrderStatus(order.getOrderStatus());
        vo.setReceiverName(order.getReceiverName());
        vo.setReceiverPhone(order.getReceiverPhone());
        vo.setReceiverAddress(order.getReceiverAddress());
        vo.setTrackingNumber(order.getTrackingNumber());
        vo.setShippingCompany(order.getShippingCompany());
        vo.setShippingTime(order.getShippingTime());
        vo.setCompletedTime(order.getCompletedTime());
        vo.setRemark(order.getRemark());
        vo.setCreateTime(order.getCreateTime());
        vo.setUpdateTime(order.getUpdateTime());

        // 转换订单明细
        if (order.getOrderItems() != null && !order.getOrderItems().isEmpty()) {
            List<OrderDetailVO.OrderItemVO> itemVOs = order.getOrderItems().stream()
                    .map(item -> {
                        OrderDetailVO.OrderItemVO itemVO = new OrderDetailVO.OrderItemVO();
                        itemVO.setId(item.getId());
                        itemVO.setProductId(item.getProductId());
                        itemVO.setProductName(item.getProductName());
                        itemVO.setProductImage(item.getProductImage());
                        itemVO.setUnitPrice(item.getUnitPrice());
                        itemVO.setQuantity(item.getQuantity());
                        itemVO.setTotalPrice(item.getTotalPrice());
                        return itemVO;
                    })
                    .collect(Collectors.toList());
            vo.setOrderItems(itemVOs);
        }

        // 添加物流信息（仅已支付订单）
        if (order.getPaymentStatus() == 1) {
            try {
                LogisticsVO logistics = calculateLogisticsInfo(order);
                vo.setLogistics(logistics);
            } catch (Exception e) {
                log.warn("计算物流信息失败，订单ID: {}, 错误: {}", order.getId(), e.getMessage());
            }
        }

        return vo;
    }

    /**
     * 计算物流信息
     * 规则：
     * - 未支付 → 待支付（状态0）
     * - 支付当天 → 待发货（状态1）
     * - 支付第2天 → 配送中（状态2）
     * - 支付第3天 → 待取件（状态3，生成取件码）
     * - 支付第4天及以后 → 已完成（状态4）
     */
    public LogisticsVO calculateLogisticsInfo(Order order) {
        LogisticsVO vo = new LogisticsVO();
        vo.setCreateTime(order.getCreateTime());

        // 如果订单已取消，不计算物流信息
        if (order.getOrderStatus() == 5) {
            return null;
        }

        // 如果订单未支付，返回待支付状态
        if (order.getPaymentStatus() == 0) {
            vo.setLogisticsStatus(0);
            vo.setStatusDesc("待支付");
            vo.setProgress(0);
            
            // 构建5个物流步骤（包含待支付）
            List<LogisticsVO.LogisticsStep> steps = new ArrayList<>();
            
            // 步骤0：待支付
            LogisticsVO.LogisticsStep step0 = new LogisticsVO.LogisticsStep();
            step0.setIndex(0);
            step0.setTitle("待支付");
            step0.setDesc("订单已创建，等待支付");
            step0.setTime(order.getCreateTime());
            step0.setCompleted(false);
            steps.add(step0);
            
            // 步骤1：待发货
            LogisticsVO.LogisticsStep step1 = new LogisticsVO.LogisticsStep();
            step1.setIndex(1);
            step1.setTitle("待发货");
            step1.setDesc("支付成功后等待发货");
            step1.setTime(null);
            step1.setCompleted(false);
            steps.add(step1);
            
            // 步骤2：配送中
            LogisticsVO.LogisticsStep step2 = new LogisticsVO.LogisticsStep();
            step2.setIndex(2);
            step2.setTitle("配送中");
            step2.setDesc("商品正在配送途中");
            step2.setTime(null);
            step2.setCompleted(false);
            steps.add(step2);
            
            // 步骤3：待取件
            LogisticsVO.LogisticsStep step3 = new LogisticsVO.LogisticsStep();
            step3.setIndex(3);
            step3.setTitle("待取件");
            step3.setDesc("商品已到达，等待取件");
            step3.setTime(null);
            step3.setCompleted(false);
            steps.add(step3);
            
            // 步骤4：已完成
            LogisticsVO.LogisticsStep step4 = new LogisticsVO.LogisticsStep();
            step4.setIndex(4);
            step4.setTitle("已完成");
            step4.setDesc("订单已完成");
            step4.setTime(null);
            step4.setCompleted(false);
            steps.add(step4);
            
            vo.setSteps(steps);
            return vo;
        }

        // 计算支付后的天数（使用支付时间而不是创建时间）
        // 兼容旧数据：如果 paymentTime 为空，使用 createTime 作为备用
        LocalDateTime paymentTime = order.getPaymentTime() != null ? order.getPaymentTime() : order.getCreateTime();
        LocalDate paymentDate = paymentTime.toLocalDate();
        LocalDate today = LocalDate.now();
        long daysSincePayment = ChronoUnit.DAYS.between(paymentDate, today);

        // 确定物流状态
        int logisticsStatus;
        String statusDesc;
        int progress;
        String pickupCode = null;

        if (daysSincePayment == 0) {
            // 支付当天：待发货
            logisticsStatus = 1;
            statusDesc = "待发货";
            progress = 20;
        } else if (daysSincePayment == 1) {
            // 支付第2天：配送中
            logisticsStatus = 2;
            statusDesc = "配送中";
            progress = 40;
        } else if (daysSincePayment == 2) {
            // 支付第3天：待取件
            logisticsStatus = 3;
            statusDesc = "待取件";
            progress = 60;
            pickupCode = generatePickupCode(order.getId());
        } else {
            // 支付第4天及以后：已完成
            logisticsStatus = 4;
            statusDesc = "已完成";
            progress = 100;
        }

        vo.setLogisticsStatus(logisticsStatus);
        vo.setStatusDesc(statusDesc);
        vo.setProgress(progress);
        vo.setPickupCode(pickupCode);

        // 构建5个物流步骤（包含待支付）
        List<LogisticsVO.LogisticsStep> steps = new ArrayList<>();

        // 步骤0：待支付（已完成）
        LogisticsVO.LogisticsStep step0 = new LogisticsVO.LogisticsStep();
        step0.setIndex(0);
        step0.setTitle("待支付");
        step0.setDesc("订单已支付");
        step0.setTime(paymentTime); // 使用支付时间（兼容旧数据）
        step0.setCompleted(true);
        steps.add(step0);

        // 步骤1：待发货
        LogisticsVO.LogisticsStep step1 = new LogisticsVO.LogisticsStep();
        step1.setIndex(1);
        step1.setTitle("待发货");
        step1.setDesc("支付成功，等待发货");
        step1.setTime(paymentTime); // 使用支付时间（兼容旧数据）
        step1.setCompleted(logisticsStatus >= 1);
        steps.add(step1);

        // 步骤2：配送中
        LogisticsVO.LogisticsStep step2 = new LogisticsVO.LogisticsStep();
        step2.setIndex(2);
        step2.setTitle("配送中");
        step2.setDesc("商品正在配送途中");
        step2.setTime(daysSincePayment >= 1 ? paymentTime.plusDays(1) : null);
        step2.setCompleted(logisticsStatus >= 2);
        steps.add(step2);

        // 步骤3：待取件
        LogisticsVO.LogisticsStep step3 = new LogisticsVO.LogisticsStep();
        step3.setIndex(3);
        step3.setTitle("待取件");
        if (pickupCode != null) {
            step3.setDesc("商品已到达，取件码：" + pickupCode);
        } else {
            step3.setDesc("商品已到达，等待取件");
        }
        step3.setTime(daysSincePayment >= 2 ? paymentTime.plusDays(2) : null);
        step3.setCompleted(logisticsStatus >= 3);
        steps.add(step3);

        // 步骤4：已完成
        LogisticsVO.LogisticsStep step4 = new LogisticsVO.LogisticsStep();
        step4.setIndex(4);
        step4.setTitle("已完成");
        step4.setDesc("订单已完成");
        step4.setTime(daysSincePayment >= 3 ? paymentTime.plusDays(3) : null);
        step4.setCompleted(logisticsStatus >= 4);
        steps.add(step4);

        vo.setSteps(steps);

        return vo;
    }

    /**
     * 生成取件码（基于订单ID的后4位，不足补0）
     */
    private String generatePickupCode(Long orderId) {
        String orderIdStr = String.valueOf(orderId);
        if (orderIdStr.length() >= 4) {
            return orderIdStr.substring(orderIdStr.length() - 4);
        } else {
            return String.format("%04d", orderId);
        }
    }

    @Override
    public IPage<OrderListVO> getAdminOrderPage(OrderQueryDTO queryDTO) {
        try {
            // 1. 先分页查询订单ID列表（只查订单表，不关联订单项）
            Page<Long> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
            IPage<Long> orderIdPage = orderMapper.selectAdminOrderIdPage(
                    page, 
                    queryDTO.getOrderNo(), 
                    queryDTO.getOrderStatus(),
                    queryDTO.getPaymentStatus());

            // 2. 如果没有数据，直接返回空结果
            if (orderIdPage.getRecords().isEmpty()) {
                return new Page<OrderListVO>(queryDTO.getCurrent(), queryDTO.getSize(), 0);
            }

            // 3. 根据订单ID列表查询完整的订单信息（包含订单项）
            List<Long> orderIds = orderIdPage.getRecords();
            List<Order> orders = orderMapper.selectOrdersByIds(orderIds);

            // 4. 转换为VO
            List<OrderListVO> orderListVOs = orders.stream()
                    .map(this::convertToOrderListVO)
                    .collect(Collectors.toList());

            // 5. 构建分页结果
            Page<OrderListVO> voPage = new Page<>(
                    orderIdPage.getCurrent(),
                    orderIdPage.getSize(),
                    orderIdPage.getTotal()
            );
            voPage.setRecords(orderListVOs);

            log.info("管理员分页查询订单列表成功，总数: {}", voPage.getTotal());
            return voPage;
        } catch (Exception e) {
            log.error("管理员分页查询订单列表失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询订单列表失败");
        }
    }

    @Override
    public OrderDetailVO getAdminOrderDetail(Long orderId) {
        try {
            Order order = orderMapper.selectOrderDetailById(orderId);
            if (order == null) {
                log.warn("订单不存在，订单ID: {}", orderId);
                throw new RuntimeException("订单不存在");
            }

            // 管理员查询订单详情无需验证订单归属
            return convertToOrderDetailVO(order);
        } catch (Exception e) {
            log.error("管理员查询订单详情失败，订单ID: {}, 错误: {}", orderId, e.getMessage(), e);
            throw new RuntimeException("查询订单详情失败");
        }
    }
}
